package com.lzxuni.modules.system;

import com.lzxuni.modules.common.controller.BaseController;
import com.lzxuni.modules.system.entity.Logo;
import com.lzxuni.modules.system.service.LogoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 〈一句话功能简述〉<br>
 *
 * @author:孙志强
 * @create:2018-05-02 21:32
 * @Modified BY:
 **/
@Controller
@RequestMapping("/LR_SystemModule/LogoImg")
public class LogoImgController extends BaseController {

	@Autowired
	private LogoService logoService;

	@RequestMapping("/PCIndex")
	public ModelAndView list(){
		ModelAndView mv = new ModelAndView("/LR_SystemModule/LogoImg/PCIndex");
		return mv;
	}
	@RequestMapping("/UploadFile")
	public Object UploadFile(MultipartFile uploadFile,MultipartFile uploadFile1,MultipartFile uploadFile2,MultipartFile uploadFile3,String code) throws Exception{
		if(uploadFile!=null){
			this.save(uploadFile,code);
		}else if(uploadFile1!=null){
			this.save(uploadFile1,code);
		}else if(uploadFile2!=null){
			this.save(uploadFile2,code);
		}else if(uploadFile3!=null){
			this.save(uploadFile3,code);
		}
		ModelAndView mv = new ModelAndView("/UserCenter/UploadFile");
		return mv;
//		R ok = R.ok();
//		return "123";
	}
	private void save(MultipartFile uploadFile,String code) throws Exception {
		Logo logo = new Logo();
		logo.setCode(code);
		InputStream inputStream = uploadFile.getInputStream();
		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
		byte[] buff = new byte[1024 * 4];
		int rc = 0;
		while ((rc = inputStream.read(buff)) != -1) {
			swapStream.write(buff, 0, rc);
		}
		byte[] in2b = swapStream.toByteArray();
		logo.setFileName(in2b);
		logoService.updateById(logo);
	}
	@RequestMapping("/GetImg")
	public void GetImg(HttpServletResponse response, String code) {
		try {
			Logo logo = logoService.getById(code);
			InputStream inputStream = new ByteArrayInputStream(logo.getFileName());
			writeImg(response, inputStream);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//用户没性别
	}

	private void writeImg(HttpServletResponse response, InputStream sbs) throws IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");
		//生成图片验证码
		BufferedImage image = ImageIO.read(sbs);
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "png", out);
	}
}
